package cn.iocoder.yudao.module.chatgpt.service.chat.impl;

import cn.iocoder.yudao.module.chatgpt.cache.ChatCache;
import cn.iocoder.yudao.module.chatgpt.controller.admin.chat.params.chat.ChatMessage;
import cn.iocoder.yudao.module.chatgpt.service.chat.ChatCacheService;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * 默认服务实现 Cache
 */
@Slf4j
public class DefaultChatCacheServiceImpl implements ChatCacheService {
    @Override
    public List<ChatMessage> history(String chatId) {
        return ChatCache.get(chatId);
    }

    @Override
    public List<ChatMessage> history(String chatId, Integer limit) {
        List<ChatMessage> list = new ArrayList<>(ChatCache.get(chatId));
        int listSize = list.size();
        int startIndex = 0;
        if (listSize > limit){
            startIndex = listSize - limit;
        }
        return list.subList(startIndex,listSize);
    }

    @Override
    public void write(String chatId, ChatMessage message) {
        List<ChatMessage> messages = ChatCache.get(chatId);
        messages.add(message);
        ChatCache.put(chatId,messages);
    }
}
